package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"hello/lib/mqttLib"
	"hello/lib/mysqlLib"
	"log"
	"strconv"
	"time"
)

type ParameterController struct {
	beego.Controller
	PublicController
}
type SettingInfo struct {
	GatewayID string `json:"gateway_id"`
	UserID string `json:"user_id"`
	MachineType float64 `json:"machine_type"`
	Params Parameter `json:"params"`
}
type Parameter struct {
	Type string `json:"type"`
	Value SettingParams `json:"value"`
}
type SettingParams struct {
	SettingTemp string `json:"st"`
	SettingSpeed string `json:"ss"`
	SettingTimeHour string `json:"sth"`
	SettingTimeMinute string `json:"stm"`
}

type PublishParams struct {
	ContentType string `json:"content_type"`
	ControlType string `json:"control_type"`
	Data int `json:"data"`
}
func (pc *ParameterController) Post() {
	reqData := pc.Ctx.Input.RequestBody
	log.Printf("received data : %s", string(reqData))
	req := SettingInfo{}
	//err := json.Unmarshal(reqData, &req)
	// 传入参数示例
	//  jstr := `{
	//	 "gateway_id": "GATEWAY",
	//	 "user_id": "user",
	//	 "params": {
	//		"type": "SETTING_PARAMS",
	//		"value": {
	//			"st": "123",
	//			"ss": "234",
	//			"sth": "1",
	//			"stm": "12"
	//	 }
	//  }
	// }`
	err := json.Unmarshal(reqData, &req)
	if err != nil {
		log.Println(err.Error())
	}

	gatewayID := req.GatewayID
	userID := req.UserID
	machineType := req.MachineType
	params := req.Params

	if params.Type != "SETTING_PARAMS" {
		pc.response("error", "not setting")
		return
	}
	c := mqttLib.NewMqttClient(mqttLib.DefaultMqttconfig, func(client mqtt.Client, msg mqtt.Message) {
		log.Print(msg)
	})
	c.Connect()
	// 15秒之后自动断开连接
	defer c.Disconnect(15*1000)
	//延迟2秒
	time.Sleep(2*time.Second)

	{
		pubparams := PublishParams{}
		if params.Value.SettingTemp != "" {
			st, err := strconv.Atoi(params.Value.SettingTemp)
			if err != nil{
				log.Printf("Error : strconv err : %s", err.Error())
			}
			if st != 0 {
				pubparams.ContentType = "setting"
				pubparams.ControlType = "temp"
				pubparams.Data = st
				payload,err := json.Marshal(pubparams)
				if err != nil {
					log.Printf("Error : Publish message marshal error : %s", err.Error())
				}
				token := c.Publish(gatewayID+mqttLib.Setting, 2, false, payload)
				if token.Error() != nil {
					log.Printf("Error : Publish message error : %s", token.Error().Error())
				}
			}
		}
		if params.Value.SettingSpeed != "" {
			ss, err := strconv.Atoi(params.Value.SettingSpeed)
			if err != nil{
				log.Printf("Error : strconv err : %s", err.Error())
			}
			if ss != 0 {
				pubparams.ContentType = "setting"
				pubparams.ControlType = "speed"
				pubparams.Data = ss
				payload,err := json.Marshal(pubparams)
				if err != nil {
					log.Printf("Error : Publish message marshal error : %s", err.Error())
				}
				token := c.Publish(gatewayID+mqttLib.Setting, 2, false, payload)
				if token.Error() != nil {
					log.Printf("Error : Publish message error : %s", token.Error().Error())
				}
			}
		}
		if params.Value.SettingTimeMinute != "" {
			stm, err := strconv.Atoi(params.Value.SettingTimeMinute)
			if err != nil{
				log.Printf("Error : strconv err : %s", err.Error())
			}
			pubparams.ContentType = "setting"
			pubparams.ControlType = "minute"
			pubparams.Data = stm
			payload,err := json.Marshal(pubparams)
			if err != nil {
				log.Printf("Error : Publish message marshal error : %s", err.Error())
			}
			token := c.Publish(gatewayID+mqttLib.Setting, 2, false, payload)
			if token.Error() != nil {
				log.Printf("Error : Publish message error : %s", token.Error().Error())
			}
		}
		if params.Value.SettingTimeHour != "" {
			sth, err := strconv.Atoi(params.Value.SettingTimeHour)
			if err != nil{
				log.Printf("Error : strconv err : %s", err.Error())
			}
			pubparams.ContentType = "setting"
			pubparams.ControlType = "hour"
			pubparams.Data = sth
			payload,err := json.Marshal(pubparams)
			if err != nil {
				log.Printf("Error : Publish message marshal error : %s", err.Error())
			}
			token := c.Publish(gatewayID+mqttLib.Setting, 2, false, payload)
			if token.Error() != nil {
				log.Printf("Error : Publish message error : %s", token.Error().Error())
			}
		}
	}
	params2db, err := json.Marshal(params)
	if err != nil {
		log.Printf("Error : Marshal params error : %s", err.Error())
	}
	err = mysqlLib.Exec("insert into hh_operation (user_id, gateway_id, device_type, setting_params) values (?,?,?,?)", userID, gatewayID, machineType, string(params2db))
	if err != nil {
		setParamsResponse := Response{}
		setParamsResponse.Status = "error"
		setParamsResponse.Errmsg = "mysql error"
		pc.Data["json"] = &setParamsResponse
		pc.ServeJSON()
	}
	//pc.response("ok", "success")
	setParamsResponse := Response{}
	setParamsResponse.Status = "ok"
	setParamsResponse.Errmsg = "success"
	pc.Data["json"] = &setParamsResponse
	pc.ServeJSON()
	//nc.response("ok", "绑定成功！")
	return
}
